﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DirectOPCClient
{
    public partial class Frmconfig : Form
    {
        public Frmconfig()
        {
            InitializeComponent();
        }

        private void cheackChanged(object obj,EventArgs e)
        {
			SetRegister(Registry.LocalMachine, checkBox1.Checked);
			XmlHelper.IniConfig.instance.SetKey("AUTOSTART", checkBox1.Checked ? "1" : "0");

		}

		private void SetRegister(RegistryKey root, bool isStartup)
		{
			RegistryKey key = root.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//打开注册表子项
			if (key == null)//如果该项不存在的话，则创建该子项
			{
				key = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", RegistryKeyPermissionCheck.ReadWriteSubTree);
			}
			//string app = "\"" + Application.StartupPath + "\\DirectOPCClient.exe\" -auto";
			
			string path = Application.ExecutablePath.ToLower(); //获取.exe当前程序路径  
																//MessageBox.Show(path);
			string name = Path.GetFileName(path);  //获得应用程序名称 


			if (isStartup)
			{
				try
				{
					key.SetValue(name, path);//设置为开机启动
					key.Close();
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message);
				}
			}
			else
			{
				try
				{
					key.DeleteValue(name);//取消开机启动
					key.Close();
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message);
				}
			}
		}

        private void Frmconfig_Load(object sender, EventArgs e)
        {
			checkBox1.Checked = (XmlHelper.IniConfig.instance.GetKey("AUTOSTART", "0") == "1");
		}
    }
}
